/*
 * @Author: ItKui<13452903663@163.com>
 * @Date: 2020-10-16 08:58:27
 * @LastEditTime: 2020-10-17 11:20:02
 * @FilePath: \wx-debuger\controllers\wx.js
 * @FileName:
 */
const axios = require("axios");
const sha1 = require("sha1");
const appId = "wxb468811edf4d5332";
const appSecret = "174ee68b7f9c40e693a62657f99f4100";

async function getSign(ctx) {
  let url = ctx.request.body.url;
  console.log(url);
  console.log("url", url);
  let { data } = await getAccessToken();
  let { access_token } = data;
  if (!access_token) {
    return (ctx.body = {
      code: 200,
      msg: "can get access_token",
      data: data,
    });
  }
  // let access_token =
  // "38_euuXqdrtFmbOVVWmuqyL3kLJy6WVdGWGg20tqnCq3ngKq3-BzUF01R7vy8XQ3X3Y2Ed2C874NZDvJPjfFDfl4HiqGlSAwgt-yvmJfwuVwIeFOLbf3louYt8cXgQWnqgHrdK0UfRi2pAEES7tXZVdAEAFHD";
  console.log("access_token", access_token);
  let {
    data: { ticket },
  } = await getTicket(access_token);
  // let ticket =
  // "LIKLckvwlJT9cWIhEQTwfG9O9MEfz8k_dKqplXDiGgHqyFEMDha97pc7My_HuhmzXO8xM6rkYSciy1zXMzXp8A";
  console.log("ticket：", ticket);
  let nonceStr = Math.random().toString(16).substring(3);
  let timestamp = Math.ceil(Date.now() / 1000);
  let str = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
  let signature = sha1(str);
  ctx.body = {
    code: 200,
    msg: "",
    data: {
      signature,
      nonceStr,
      appId,
      timestamp,
    },
  };
}

function getTicket(access_token) {
  let request_url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;
  console.log(`getTicketUrl:${request_url}`);
  return axios.get(request_url);
}

function getAccessToken() {
  let request_url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;
  console.log(`getAccessTokenUrl:${request_url}`);
  return axios.get(request_url);
}

module.exports = {
  getSign,
};
